define(function () {
    'use strict';

    function ctrl($scope,$state,$stateParams,DictionaryService,$ionicLoading,
                  $ionicHistory,CommonService,LocalCacheService,ConcernService,WebService) {
        var par = $scope.param = new Array();
        par.content = "login page";
        $scope.$on('$ionicView.beforeEnter', function() {
            init();
        });

        function init(){
            $scope.login.password = null;
            $scope.login.captcha = null;
            $scope.login.rememberAccount = true;
            $scope.login.historyOpen = false;
            $scope.login.contentFocus = false;
            $scope.login.pwdFocus = false;
            $scope.login.captchaFocus = false;
            if(LocalCacheService.getAccountList()){
                $scope.login.accountList  = LocalCacheService.getAccountList().split(",");
            }else {
                $scope.login.accountList  = new Array();
            }
            var account = LocalCacheService.getAccount();
            var rememberAccount = LocalCacheService.getRememberAccount();
            if(rememberAccount != 0) {
                $scope.login.account_content = account;
            } else {
                $scope.login.rememberAccount = false;
                $scope.login.account_content = null;
            }

            $scope.branchs = DictionaryService.getBranchs();

            var user = LocalCacheService.getUser();
            if(user) {
                var from = $stateParams["from"];
                if(from && from != "login"){
                    $state.go(from, angular.fromJson($stateParams["fromParams"]));
                } else {
                    $state.go("tab.account-index");
                }
            }
        }


        $scope.closeHistory = function(e){
            if($scope.login.historyOpen&&e.toElement.className.indexOf('unClose')==-1){
                $scope.login.historyOpen =false;
            }
        };

        $scope.openHistory = function(e){
            if(!$scope.login.historyOpen){
                $scope.login.historyOpen=true;
            }
        };

        $scope.selectAccount = function(account_content){
            $scope.login.account_content=account_content;
            $scope.login.historyOpen = false;
        };
        $scope.delAccount = function(index){
            $scope.login.accountList.splice(index,1);
            LocalCacheService.setAccountList($scope.login.accountList.join(","));
        };

        $scope.login = function (){
            var account_content = $.trim($scope.login.account_content);
            var password =$.trim($scope.login.password);
            /*if("" == account_content || "" == password){
             CommonService.showAlert({message:"请输入账号和密码"});
             return false;
             }*/
            /*if($.trim($scope.login.captcha) == ""){
             CommonService.showAlert({message:"请输入验证码"});
             return false;
             }*/
            if(phoneRegex.test(account_content)){
                loginEvent();
            }else{
                if($scope.branchs == ""){
                    CommonService.showAlert({message:"营业部信息获取失败，请重试"});
                }else{
                    var isAccount = false;
                    var branArr = $scope.branchs.split(",");
                    for(var i=0;i<branArr.length;i++){
                        var branch_no = branArr[i];
                        if(!isNaN(account_content) && account_content.indexOf(branch_no) == 0){
                            loginEvent();
                            isAccount = true;
                            break;
                        }
                    }
                    if(!isAccount){
                        CommonService.showAlert({message:"手机号或客户号输入有误！"});
                    }
                }
            }
        };

        $scope.clickPassword = function() {
            $("#password").triggerHandler('click');
        };

        $scope.myKeyup = function(e){
            var keycode = window.event?e.keyCode:e.which;
            if(keycode==13){
                $scope.login();
            }
        };

        function loginEvent(){
            var params = buildParams();
            $ionicLoading.show();
            //登陆请求
            WebService.login(params).then(
                function(data){
                    LocalCacheService.setRememberAccount($scope.login.rememberAccount ?  1 : 0);
                    if($scope.login.rememberAccount) {
                        LocalCacheService.setAccount(params.account_content);
                        //本地缓存用户信息列表
                        if($scope.login.accountList.indexOf(params.account_content)==-1){
                            $scope.login.accountList.push(params.account_content);
                            if($scope.login.accountList.length>5){
                                $scope.login.accountList.shift();
                            }
                            LocalCacheService.setAccountList($scope.login.accountList.join(","));
                        }

                    } else {
                        LocalCacheService.removeAccount();
                    }
                    if(typeof Messenger != 'undefined') {
                        Messenger.sendMsg("ym_profileSignIn",{PUID: $scope.login.account_content} ,null,null);
                    }
                    var user = {};
                    user.token = data.token;
                    LocalCacheService.setUser(user);
                    WebService.getUserInfo().then(
                        function (result){
                            LocalCacheService.setUser(result);
                            $ionicLoading.hide();

                            var to = $stateParams["to"];
                            if(to && to.indexOf("open-") == -1){
                                $state.go(to, angular.fromJson($stateParams["toParams"]));

                            } else if(sessionStorage["login_next_page"]){
                                var next_url = sessionStorage["login_next_page"];
                                $state.go(next_url);
                            } else if($ionicHistory.backView() && $ionicHistory.backView().stateName.indexOf("open-") == -1) {
                                $ionicHistory.goBack();
                            } else {
                                $state.go("tab.account-assets-index");
                            }
                        }, function(result){
                            LocalCacheService.removeUser();
                            CommonService.showConfig({message:"获取用户信息失败"});
                        }
                    )
                }, function(data){
                    if(data  && data.error_no == "XCM-100008"){
                        CommonService.showAlert({message:"data"});
                        $scope.showCaptcha();
                    }
                }
            );
            //同步用户关注信息
            WebService.syncUserCare(params);
        }

        var phoneRegex = /^1[0-9][0-9]\d{8}$/;

        function buildParams(){
            var params = {};
            var account_content = $.trim($scope.login.account_content)?$.trim($scope.login.account_content):"66000068";
            $.extend(params,{account_content:account_content,password:$.trim($scope.login.password)?$.trim($scope.login.password):"111111",
                captcha_str:$scope.login.captcha_str, captcha : $scope.login.captcha, time_stamp : $scope.login.time_stamp});
            var input_content = "1";
            if (phoneRegex.test(account_content)){
                input_content = "b";
            }
            $.extend(params,{input_content:input_content});
            $.extend(params,{cares_str:ConcernService.getConcernList()});
            return params;
        }

        $scope.onBackKeyDown = function () {
//            var from = $stateParams["from"];
            if($.cookie("back_url_2") || ($.cookie("_r_u_l") && $.cookie("_r_u_l").indexOf("from=2") !=-1)) {
                Messenger.send("close");
            } else if(CommonService.isBuyExperience()) { //理财体验活动
                var to_state = LocalCacheService.get("lcty_state");
                $state.go(to_state.stateName, to_state.stateParams);
            }else if($ionicHistory.backView() && "sessionOut" != $stateParams["w"]) {
                $ionicHistory.goBack();
            } else {
                $state.go("tab.index");
            }
        };
    }

    ctrl.$inject = ['$scope','$state','$stateParams','DictionaryService','$ionicLoading',
        '$ionicHistory','CommonService','LocalCacheService','ConcernService','WebService'];
    return ctrl;
});
